<?php
namespace app\admin\controller;

use app\admin\model\Admin;
use think\captcha\Captcha;
use think\Controller;
use think\Request;
use think\Session;

class Login extends Controller{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=Request::instance();
    }
    public function index(){
        return $this->fetch();
    }
    public function verify(){
        $captcha=new Captcha([
            'useCurve'=>false
        ]);
        return $captcha->entry();

    }
    public function login(){
        $username=input('username');
        $password=input('password');
        $code=input('code');
        if(empty($username)||empty($password)||empty($code)){
            $result=[
                'status'=>0,
                'msg'=>'提交的数据不合法'
            ];
            return json($result);
        }
        $captcha=new Captcha();
        $res=$captcha->check($code);
        if (!$res) {
            return json([
                'status' => 0,
                'msg' => '验证码不正确'
            ]);
        }
        $model = new Admin();
        $where = [
            'username' => $username
        ];
        $node = $model->getOne($where);

        $salt_password=md5(md5($password).$node['salt']);
        if (is_null($node) == false && $node['password'] == $salt_password) {
            Session::set('admin_id',$node['admin_id']);
            Session::set('admin',$node);
            return json([
                'status'=>1,
                'msg' => '登录成功'
            ]);
        } else {
            return json([
                'status'=>0,
                'msg' => '用户名或密码错误'
            ]);
        }

    }
}